package com.gzwanchuang.xhgj.ui.page.main;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.gzwanchuang.architecture.utils.GsonUtils;
import com.gzwanchuang.architecture.utils.ValidateUtils;
import com.gzwanchuang.xhgj.R;
import com.gzwanchuang.xhgj.bridge.data.repository.Apis;
import com.gzwanchuang.xhgj.bridge.data.repository.WebApis;
import com.gzwanchuang.xhgj.bridge.request.HomeRequestViewModel;
import com.gzwanchuang.xhgj.bridge.state.main.HomeFragmentViewModel;
import com.gzwanchuang.xhgj.databinding.FragmentHomeBinding;
import com.gzwanchuang.xhgj.help.FloatCalculatorHelp;
import com.gzwanchuang.xhgj.net.NetworkManager;
import com.gzwanchuang.xhgj.net.interfaces.OnRequestCallBack;
import com.gzwanchuang.xhgj.proto.Bank;
import com.gzwanchuang.xhgj.proto.MemberOuterClass;
import com.gzwanchuang.xhgj.proto.Merchantservice;
import com.gzwanchuang.xhgj.ui.base.BaseFragment;
import com.gzwanchuang.xhgj.ui.dialog.RecycleViewDialog;
import com.gzwanchuang.xhgj.ui.dialog.VipHasDialog;
import com.gzwanchuang.xhgj.ui.dialog.VipNotDialog;
import com.google.protobuf.InvalidProtocolBufferException;
import com.gzwanchuang.xhgj.ui.web.ui.WebViewActivity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import kale.ui.view.dialog.EasyDialog;

/**
 * 文件名 : HomeRootFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/12/24 16:20
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */
public class HomeFragment extends BaseFragment {
    private FragmentHomeBinding mBinding;
    private HomeFragmentViewModel mViewModel;
    private HomeRequestViewModel mRequestViewModel;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(HomeFragmentViewModel.class);
        mRequestViewModel = ViewModelProviders.of(this).get(HomeRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        mBinding = FragmentHomeBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mBinding.setVm(mViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mRequestViewModel.getShowList().observe(this, get_show_list -> {
            List<String> bannerFeedList = new ArrayList<>();
            List<String> bannerTitleList = new ArrayList<>();
            for (int i = 0; i < get_show_list.getAdvListList().size(); i++) {
                bannerFeedList.add(get_show_list.getAdvListList().get(i).getAdvCode());
                bannerTitleList.add("");
            }

            mViewModel.bannerFeedList.addAll(bannerFeedList);
            mViewModel.bannerTitleList.addAll(bannerTitleList);
        });


        mRequestViewModel.getBankList().observe(this, banks -> {
            if (ValidateUtils.isValidate(banks))  // 判断是有刷Vip的信用卡用
            {
                showVipHasDialog(banks);
            } else {
                showVipNotDialog();
            }
        });


        mSharedViewModel.homeLoad.observe(this, isLoad -> {
            NetworkManager.INSTANCE.post(Apis.limit_list, new OnRequestCallBack() {
                @Override
                public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                    Merchantservice.limit_list limit_list = Merchantservice.limit_list.parseFrom(bytes);
                    Log.e("limit_list", limit_list.toString());
                    float posLimit = Float.parseFloat(limit_list.getPosLimit());
                    float scanLimit = Float.parseFloat(limit_list.getScanLimit());
                    float posLeft = Float.parseFloat(limit_list.getPosLeft());
                    float scanLeft = Float.parseFloat(limit_list.getScanLeft());
                    float totalLimit = FloatCalculatorHelp.add(posLimit, scanLimit);
                    float totalPost = FloatCalculatorHelp.add(posLeft, scanLeft);
                    float today = FloatCalculatorHelp.subtract(totalLimit, totalPost);
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String todayS = decimalFormat.format(today);//format 返回的是字符串
                    String shengyuS = decimalFormat.format(totalPost);//format 返回的是字符串
                    mBinding.tvToday.setText(todayS);
                    mBinding.tvShengYu.setText(shengyuS);
                    Float total = posLimit + scanLimit;
                    int todayPe = (int) ((today / total) * 100);
                    mBinding.circularProgressView.setProgress(todayPe, todayPe * 15);
                    mViewModel.persen.set(todayPe + "%");

                }

                @Override
                public void onError(int code, String errorMessage) {
                }
            });
        });


        mRequestViewModel.getBanks().observe(this, banks -> {
            mViewModel.banks.addAll(banks);
        });

        // 获取信用卡支持列表
        mRequestViewModel.get_support("2", "1");  // 类型:1-结算卡;2-信用卡   // VIP支持：1-支持;2-所有

        // 获取banner
        mRequestViewModel.getbanner();

        // 获取关于图
        mRequestViewModel.informationIndex();


        NetworkManager.INSTANCE.post(Apis.limit_list, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Merchantservice.limit_list limit_list = Merchantservice.limit_list.parseFrom(bytes);
                Log.e("limit_list", limit_list.toString());
                float posLimit = Float.parseFloat(limit_list.getPosLimit());
                float scanLimit = Float.parseFloat(limit_list.getScanLimit());
                float posLeft = Float.parseFloat(limit_list.getPosLeft());
                float scanLeft = Float.parseFloat(limit_list.getScanLeft());
                float totalLimit = FloatCalculatorHelp.add(posLimit, scanLimit);
                float totalPost = FloatCalculatorHelp.add(posLeft, scanLeft);
                float today = FloatCalculatorHelp.subtract(totalLimit, totalPost);
                DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                String todayS = decimalFormat.format(today);//format 返回的是字符串
                String shengyuS = decimalFormat.format(totalPost);//format 返回的是字符串
                mBinding.tvToday.setText(todayS);
                mBinding.tvShengYu.setText(shengyuS);
                Float total = posLimit + scanLimit;
                int todayPe = (int) ((today / total) * 100);
                mBinding.circularProgressView.setProgress(todayPe, todayPe * 15);
                mViewModel.persen.set(todayPe + "%");

            }

            @Override
            public void onError(int code, String errorMessage) {
            }
        });


        NetworkManager.INSTANCE.post(Apis.system_log, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                MemberOuterClass.SysteLog systeLog = MemberOuterClass.SysteLog.parseFrom(bytes);
                List<MemberOuterClass.SysteLog.SystemLogList> systemLogLists = systeLog.getSystemLogListList();
                if (systemLogLists.size() > 0) {
                    mViewModel.pm_text.set(systemLogLists.get(0).getPushTitle() + " " + systemLogLists.get(0).getPushMessage());
                } else {
                    mViewModel.pm_text.set("暂无消息");
                }
            }

            @Override
            public void onError(int code, String errorMessage) {
                mViewModel.pm_text.set(errorMessage);
            }
        });


        NetworkManager.INSTANCE.post(Apis.get_member_info, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                MemberOuterClass.Member member = MemberOuterClass.Member.parseFrom(response);
                mViewModel.memberName.set("Hi," + member.getMemberName());
                if (member.getReUpload().equals("1"))
                {
                    mBinding.ivBianGeng.setVisibility(View.VISIBLE);
                }else
                { mBinding.ivBianGeng.setVisibility(View.GONE);}
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
            }
        });


        NetworkManager.INSTANCE.post(Apis.service_agreement, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Merchantservice.service_agreement member = Merchantservice.service_agreement.parseFrom(response);
                if (member.getIsVip().equals("1")) {
                    mBinding.llXiangHui.setVisibility(View.VISIBLE);
                    mViewModel.vipImg.set(member.getLogo());
                } else {
                    mBinding.llXiangHui.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
            }
        });


    }


    // 弹出vip信用卡框
    private void showVipHasDialog(List<Bank.bank> banks) {
        VipHasDialog.Builder builder = new VipHasDialog.Builder(mActivity);
        builder.setData(GsonUtils.serializedToJson(banks));
        builder.setOnDialogClickListenerOne((view) -> showBank());
        builder.setOnDialogClickListenerTow(v -> {
            Bundle bundle = new Bundle();
            bundle.putInt("type", 1);
            nav().navigate(R.id.action_mainRootFragment_to_shuaKaFragment, bundle);
        });
        builder.setOnDialogClickListenerThree((view) -> nav().navigate(R.id.action_mainRootFragment_to_bindXinCardFragment));
        EasyDialog build = builder.build();
        build.setCancelable(false);
        build.show(getChildFragmentManager());
    }


    // 弹出没有vip信用卡框
    private void showVipNotDialog() {
        VipNotDialog.Builder builder = new VipNotDialog.Builder(mActivity);
        builder.setOnDialogClickListenerOne((view) -> showBank());
        builder.setOnDialogClickListenerTow((view) -> nav().navigate(R.id.action_mainRootFragment_to_bindXinCardFragment));
        EasyDialog build = builder.build();
        build.setCancelable(false);
        build.show(getChildFragmentManager());
    }


    // 展示信用卡支持列表
    private void showBank() {
        if (ValidateUtils.isValidate(mViewModel.banks)) {
            RecycleViewDialog.Builder builder = new RecycleViewDialog.Builder(mActivity);
            builder.setData(GsonUtils.serializedToJson(mViewModel.banks)).setTitle("VIP收款支持银行");
            EasyDialog build = builder.build();
            build.show(getChildFragmentManager());
        } else {
            showShortToast("暂无支持银行");
        }
    }

    public class ClickProxy {
        public void back() {
        }

        public void GoToNext(View view) {
            switch (view.getId()) {
                case R.id.ll_zhan_dan:
                    nav().navigate(R.id.action_mainRootFragment_to_zhanDanFragment);
                    break;
                case R.id.ll_jie_suan_ka:
                    nav().navigate(R.id.action_mainRootFragment_to_bankCardRenFragment);
                    break;
                case R.id.ll_ka_bao:
                case R.id.tv_ti_er:
                    nav().navigate(R.id.action_mainRootFragment_to_tiErRenFragment);
                    break;
                case R.id.ll_she_bei:
                    nav().navigate(R.id.action_mainRootFragment_to_kaBaoFragment);
                    break;
                case R.id.tv_system_message:
                    nav().navigate(R.id.action_mainRootFragment_to_messageFragment);
                    break;
                case R.id.ll_xiang_hui:
                    nav().navigate(R.id.action_mainRootFragment_to_xiangHuiRenFragment);
                    break;
                case R.id.ll_ma_ti:
                    WebViewActivity.startActivity(mActivity, WebApis.mashang);
                    break;
                case R.id.ll_fen_kong:
                    WebViewActivity.startActivity(mActivity, WebApis.risk);
                    break;
                case R.id.iv_bian_geng:
                    WebViewActivity.startActivity(mActivity, WebApis.ChangeOfIDCard);
                    break;

            }
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            NetworkManager.INSTANCE.post(Apis.limit_list, new OnRequestCallBack() {
                @Override
                public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                    Merchantservice.limit_list limit_list = Merchantservice.limit_list.parseFrom(bytes);
                    Log.e("limit_list", limit_list.toString());
                    float posLimit = Float.parseFloat(limit_list.getPosLimit());
                    float scanLimit = Float.parseFloat(limit_list.getScanLimit());
                    float posLeft = Float.parseFloat(limit_list.getPosLeft());
                    float scanLeft = Float.parseFloat(limit_list.getScanLeft());
                    float totalLimit = FloatCalculatorHelp.add(posLimit, scanLimit);
                    float totalPost = FloatCalculatorHelp.add(posLeft, scanLeft);
                    float today = FloatCalculatorHelp.subtract(totalLimit, totalPost);
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String todayS = decimalFormat.format(today);//format 返回的是字符串
                    String shengyuS = decimalFormat.format(totalPost);//format 返回的是字符串
                    mBinding.tvToday.setText(todayS);
                    mBinding.tvShengYu.setText(shengyuS);
                    Float total = posLimit + scanLimit;
                    int todayPe = (int) ((today / total) * 100);
                    mBinding.circularProgressView.setProgress(todayPe, todayPe * 15);
                    mViewModel.persen.set(todayPe + "%");

                }

                @Override
                public void onError(int code, String errorMessage) {
                }
            });
        }
    }
}
